﻿using DataCapture.Helper;
using static DataCapture.Helper.PublicHelp;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System;

namespace DataCapture.DeviceDataSave;
/// <summary>
/// 基础管上料
/// </summary>
public class DeviceJCGSLJ : DeviceBase
{
    private DeviceData<JCGSLJ_PLC_ActionDataModel> deviceData;//MQ动作数据
    private DeviceData<List<AlarmData>> DeviceAlarmDataData;//MQ报警数据
    private Func<Func<string, int>, JCGSLJ_PLC_ActionDataModel> mapper;
    public DeviceJCGSLJ(string plcName, ElementConfig elementConfig, CancellationToken cancellationToken) : base(plcName, elementConfig)
    {
        deviceData = new DeviceData<JCGSLJ_PLC_ActionDataModel>();
        DeviceAlarmDataData = new DeviceData<List<AlarmData>>();


        List<PlcPart> plcParts = new List<PlcPart>();
        foreach (var moduleConfig in elementConfig.ModuleConfig)
        {
            if (moduleConfig.PartList == null || moduleConfig.PartList.Count < 0)
            {
                continue;
            }
            plcParts.AddRange(moduleConfig.PartList);
        }
        mapper = MapperCache.GetMapper<JCGSLJ_PLC_ActionDataModel>(_cachedDelegates, plcParts.ToArray());
        //读取动作数据
        Task.Run(() =>
        {
            ReadActionData(cancellationToken, (() =>
            {
                if (mapper == null)
                {
                    return;
                }
                //数据缓存获取PLC数据
                Func<string, int> getData = GetData;

                // 4. 执行映射，生成实体对象
                var result = mapper(getData);

                //// 5. 输出结果
                //Console.WriteLine("映射结果：");
                //Console.WriteLine(result);
                JCGSLJ_PLC_ActionDataModel data = result;
                deviceData.timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                deviceData.deviceId = elementConfig.DeviceId;
                deviceData.dataType = "Action";
                deviceData.data = data;
                // 转发数据
                MQTTConsoleServer.Instance.ForwardData(deviceData, topic);
            }));

        }, cancellationToken);
        //读取报警数据
        Task.Run(() =>
        {
            ReadAlarmData(cancellationToken, () =>
            {
                if (AlarmMqDatas != null && AlarmMqDatas.Count > 0)
                {
                    DeviceAlarmDataData.timeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    DeviceAlarmDataData.deviceId = elementConfig.DeviceId;
                    DeviceAlarmDataData.dataType = "Alarm";
                    DeviceAlarmDataData.data = AlarmMqDatas;
                    //转发数据
                    MQTTConsoleServer.Instance.ForwardData(DeviceAlarmDataData, "DeviceAlarmData");
                }
            });

        }, cancellationToken);
        Log4NetHelper.Debug($"【基础管上料{elementConfig.DeviceId}】数据采集已经启动", true);
    }
}